package world.snowcrystal.openapi.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import world.snowcrystal.commons.exception.BusinessException;
import world.snowcrystal.commons.model.dto.BaseResponse;
import world.snowcrystal.commons.model.dto.DeleteRequest;
import world.snowcrystal.commons.model.dto.invokelog.UserInvokeLogAddRequest;
import world.snowcrystal.commons.model.dto.invokelog.UserInvokeLogQueryRequest;
import world.snowcrystal.commons.model.dto.invokelog.UserInvokeLogUpdateRequest;
import world.snowcrystal.commons.model.entity.User;
import world.snowcrystal.commons.model.entity.UserInvokeLog;
import world.snowcrystal.commons.model.enums.ApplicationResponseStatusCode;
import world.snowcrystal.commons.model.enums.SortOrderEnum;
import world.snowcrystal.commons.model.enums.UserRoleEnum;
import world.snowcrystal.commons.service.UserInvokeLogService;
import world.snowcrystal.commons.service.UserService;
import world.snowcrystal.openapi.annotation.AuthorityCheck;
import world.snowcrystal.openapi.utils.ResultUtils;

import java.util.List;

/**
 * 接口管理
 */
//@RestController
//@RequestMapping("/interfaceInfo")
@Slf4j
public class InterfaceInvokeLogController {

    @Resource
    private UserInvokeLogService invokeLogService;

    @Resource
    private UserService userService;


    // region 增删改查

    /**
     * 创建
     */
    @PostMapping("/add")
    @AuthorityCheck(value = UserRoleEnum.ADMIN)
    public BaseResponse<Long> addUserInvokeLog(@RequestBody UserInvokeLogAddRequest addRequest, HttpServletRequest request) {
        if (addRequest == null) {
            throw new BusinessException(ApplicationResponseStatusCode.PARAMS_ERROR);
        }
        UserInvokeLog userInvokeLog = new UserInvokeLog();
        BeanUtils.copyProperties(addRequest, userInvokeLog);
        // 校验
        User loginUser = userService.getLoginUser(request);
        userInvokeLog.setUserId(loginUser.getId());
        invokeLogService.validUserInvokeLog(userInvokeLog, true);
        boolean result = invokeLogService.save(userInvokeLog);
        if (!result) {
            throw new BusinessException(ApplicationResponseStatusCode.OPERATION_ERROR);
        }
        Long newInvokeLogId = userInvokeLog.getId();
        return ResultUtils.success(newInvokeLogId);
    }

    /**
     * 删除
     */
    @PostMapping("/delete")
    @AuthorityCheck(value = UserRoleEnum.ADMIN)
    public BaseResponse<Boolean> deleteUserInvokeLog(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ApplicationResponseStatusCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        UserInvokeLog oldUserInvokeLog = invokeLogService.getById(id);
        if (oldUserInvokeLog == null) {
            throw new BusinessException(ApplicationResponseStatusCode.NOT_FOUND_ERROR);
        }
        // 仅本人或管理员可删除
        if (!oldUserInvokeLog.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ApplicationResponseStatusCode.NO_AUTH_ERROR);
        }
        boolean b = invokeLogService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新
     *
     * @param interfaceInfoUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    @AuthorityCheck(value = UserRoleEnum.ADMIN)
    public BaseResponse<Boolean> updateUserInvokeLog(@RequestBody UserInvokeLogUpdateRequest interfaceInfoUpdateRequest,
                                                     HttpServletRequest request) {
        if (interfaceInfoUpdateRequest == null || interfaceInfoUpdateRequest.getId() <= 0) {
            throw new BusinessException(ApplicationResponseStatusCode.PARAMS_ERROR);
        }
        UserInvokeLog interfaceInfo = new UserInvokeLog();
        BeanUtils.copyProperties(interfaceInfoUpdateRequest, interfaceInfo);
        User user = userService.getLoginUser(request);
        interfaceInfo.setUserId(user.getId());
        // 参数校验
        invokeLogService.validUserInvokeLog(interfaceInfo, false);
        long id = interfaceInfoUpdateRequest.getId();
        // 判断是否存在
        UserInvokeLog oldUserInvokeLog = invokeLogService.getById(id);
        if (oldUserInvokeLog == null) {
            throw new BusinessException(ApplicationResponseStatusCode.NOT_FOUND_ERROR);
        }
        // 仅本人或管理员可修改
        if (!oldUserInvokeLog.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ApplicationResponseStatusCode.NO_AUTH_ERROR);
        }
        boolean result = invokeLogService.updateById(interfaceInfo);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     */
    @GetMapping("/get")
    public BaseResponse<UserInvokeLog> getUserInvokeLogById(Long id) {
        if (id <= 0) {
            throw new BusinessException(ApplicationResponseStatusCode.PARAMS_ERROR);
        }
        UserInvokeLog interfaceInfo = invokeLogService.getById(id);
        return ResultUtils.success(interfaceInfo);
    }

    /**
     * 获取列表（仅管理员可使用）
     */
    @AuthorityCheck(value = UserRoleEnum.ADMIN)
    @GetMapping("/list")
    public BaseResponse<List<UserInvokeLog>> listUserInvokeLog(UserInvokeLogQueryRequest interfaceInfoQueryRequest) {
        UserInvokeLog interfaceInfoQuery = new UserInvokeLog();
        if (interfaceInfoQueryRequest != null) {
            BeanUtils.copyProperties(interfaceInfoQueryRequest, interfaceInfoQuery);
        }
        QueryWrapper<UserInvokeLog> queryWrapper = new QueryWrapper<>(interfaceInfoQuery);
        List<UserInvokeLog> interfaceInfoList = invokeLogService.list(queryWrapper);
        return ResultUtils.success(interfaceInfoList);
    }

    /**
     * 分页获取列表
     */
    @PostMapping("/list/page")
    public BaseResponse<Page<UserInvokeLog>>
    listUserInvokeLogByPage(@RequestBody UserInvokeLogQueryRequest interfaceInfoQueryRequest,
                            HttpServletRequest request) {

        log.debug("listUserInvokeLogByPage, request:{}", JSONUtil.toJsonStr(interfaceInfoQueryRequest));
        if (interfaceInfoQueryRequest == null) {
            throw new BusinessException(ApplicationResponseStatusCode.PARAMS_ERROR);
        }
        UserInvokeLog interfaceInfoQuery = new UserInvokeLog();
        BeanUtils.copyProperties(interfaceInfoQueryRequest, interfaceInfoQuery);
        Long current = interfaceInfoQueryRequest.getCurrent();
        Long size = interfaceInfoQueryRequest.getPageSize();
        String sortField = interfaceInfoQueryRequest.getSortField();
        String sortOrder = interfaceInfoQueryRequest.getSortOrder();
        // 限制爬虫
        if (size > 50) {
            throw new BusinessException(ApplicationResponseStatusCode.PARAMS_ERROR);
        }
        QueryWrapper<UserInvokeLog> queryWrapper = new QueryWrapper<>(interfaceInfoQuery);
        queryWrapper.orderBy(StringUtils.isNotBlank(sortField),
                SortOrderEnum.ASCENDING.getValue().equals(sortOrder), sortField);
        Page<UserInvokeLog> interfaceInfoPage = invokeLogService.page(new Page<>(current, size), queryWrapper);
        return ResultUtils.success(interfaceInfoPage);
    }

    // endregion


}
